/**
 * @Author: lena
 * @Description:多态
 * @Version: 1.0.0
 * @Date: 2021/8/25 13:57
 */

package oop

import "fmt"

type Animal interface {
	Sleep()
	GetName() string
	GetType() string
}

// 猫：实现接口Animal所有公有方法
type Cat struct {
	Name string
}

func (this *Cat) Sleep() {
	fmt.Println("cat:", this.Name, "is sleep...")
}

func (this *Cat) GetName() string {
	return this.Name
}

func (this *Cat) GetType() string {
	return "cat"
}

// 狗：实现接口Animal所有公有方法
type Dog struct {
	Name string
}

func (this *Dog) Sleep() {
	fmt.Println("dog:", this.Name, "is sleep...")
}

func (this *Dog) GetName() string {
	return this.Name
}

func (this *Dog) GetType() string {
	return "dog"
}

func Run(animal Animal) string {
	// 多态：传入接口animal，会根据实际值调用方法
	return animal.GetType()
}

func Polymorphic() {
	var animal1 Animal = &Cat{"little cat"}
	animal1.Sleep()                // cat: little cat is sleep...
	fmt.Println(animal1.GetName()) // little cat
	fmt.Println(animal1.GetType()) // cat
	fmt.Println("--------------------------")
	var animal2 Animal = &Dog{"little dog"}
	animal2.Sleep()                // dog: little dog is sleep...
	fmt.Println(animal2.GetName()) // little dog
	fmt.Println(animal2.GetType()) // dog
	fmt.Println("--------------------------")
	fmt.Println(Run(animal1)) // cat
	fmt.Println(Run(animal2)) // dog
}
